package homelesspartners.client.widgets;

import homelesspartners.client.model.City;

import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HomeTabWidget extends Composite {

	private DockPanel panel = new DockPanel();
	private MenuBar menu = new MenuBar();
	private Frame frame = new Frame();
	private VerticalPanel cityPanel = new VerticalPanel();
	private HTML title =
			new HTML("<br />To read the personal stories of homeless people, click your city below:<br /><br />");

	private ArrayList stats = null;

	private static HomeTabWidget instance = new HomeTabWidget();

	public HomeTabWidget() {
		initWidget(panel);
		panel.add(menu, DockPanel.NORTH);
		panel.add(frame, DockPanel.CENTER);
		frame.setStyleName("gwt-Frame");
		frame.setHeight("700px");
		frame.setUrl("./pages/welcome.html");

		VerticalPanel sidePanel = new VerticalPanel();
		sidePanel.add(cityPanel);
		sidePanel.add(new SponsorsWidget());

		panel.add(sidePanel, DockPanel.EAST);
		cityPanel.add(new Label("Loading cities..."));
		cityPanel.setWidth("200px");

		menu.addItem(new MenuItem("welcome", new Command() {

			public void execute() {
				frame.setUrl("./pages/welcome.html");
			}
		}));

		menu.addItem(new MenuItem("questions", new Command() {

			public void execute() {
				frame.setUrl("./pages/faq.html");
			}
		}));

		menu.addItem(new MenuItem("about", new Command() {

			public void execute() {
				frame.setUrl("./pages/about.html");
			}
		}));

	}

	public static HomeTabWidget getInstance() {
		return instance;
	}

	public void refresh() {
		cityPanel.clear();
		cityPanel.add(title);
		ArrayList cities = City.getCities();
		if (cities != null) {
			for (Iterator cityIter = cities.iterator(); cityIter.hasNext();) {
				final City city = (City) cityIter.next();
				CityWidget cityWidget = new CityWidget(city);
				cityPanel.add(cityWidget);
			}
		}

		if (stats != null) {
			cityPanel.add(new HTML("<br /><br /><br />Number of people who have recieved a gift: <b>" + stats.get(0).toString() + "</b>"));
			cityPanel.add(new HTML("<br />Number of people who still need at least one:"));
			cityPanel.add(new HTML(stats.get(1).toString()));
		}
	}

	public void updateStats(ArrayList theStats) {
		stats = theStats;
		refresh();
	}
}
